<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="学号" prop="studentNumber">
        <el-input
          v-model="queryParams.studentNumber"
          placeholder="请输入学号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="学生姓名" prop="studentName">
        <el-input
          v-model="queryParams.studentName"
          placeholder="请输入学生姓名"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="班级名称" prop="classId">
        <el-select v-model="queryParams.classId" placeholder="请选择班级" clearable>
          <el-option
            v-for="item in gradeOptions"
            :key="item.classId"
            :label="item.className"
            :value="item.classId"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['manage:student:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['manage:student:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['manage:student:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['manage:student:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Upload"
          @click="handleImport"
          v-hasPermi="['manage:student:import']"
        >导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
        type="info"
        plain
        icon="Download"
        @click="handleImportTemplate"
        >下载模板</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="studentList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" :selectable="rowSelectionDisabled" />
      <el-table-column label="序号" align="center" type="index" width="50" />
      <el-table-column label="学号" align="center" prop="studentNumber" />
      <el-table-column label="学生姓名" align="center" prop="studentName" />
      <el-table-column label="班级名称" align="center" min-width="100">
        <template #default="scope">
          {{ getClassName(scope.row.classId) }}
        </template>
      </el-table-column>
      <el-table-column label="联系电话" align="center" prop="phone" />
      <el-table-column label="邮箱" align="center" prop="email" min-width="120" />
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <el-tag :type="scope.row.status === 0 ? 'success' : 'danger'">
            <dict-tag :options="tgs_status" :value="scope.row.status"/>
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" show-overflow-tooltip />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" 
            v-hasPermi="['manage:student:edit']"
            :disabled="scope.row.studentNumber === '1000000001'">修改</el-button>
          <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)" 
            v-hasPermi="['manage:student:remove']"
            :disabled="scope.row.studentNumber === '1000000001'">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改学生信息对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="studentRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="学号" prop="studentNumber">
          <el-input v-model="form.studentNumber" placeholder="请输入学号" maxlength="10" />
        </el-form-item>
        <el-form-item label="学生姓名" prop="studentName">
          <el-input v-model="form.studentName" placeholder="请输入学生姓名" maxlength="30" />
        </el-form-item>
        <el-form-item label="班级名称" prop="classId">
          <el-select v-model="form.classId" placeholder="请选择班级">
            <el-option
              v-for="item in gradeOptions"
              :key="item.classId"
              :label="item.className"
              :value="item.classId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入联系电话" maxlength="11" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入邮箱" maxlength="50" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in tgs_status"
              :key="dict.value"
              :label="parseInt(dict.value)"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" maxlength="500" show-word-limit />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 数据导入对话框 -->
    <el-dialog title="数据导入" v-model="excelOpen" width="400px" append-to-body>
      <el-upload
        ref="uploadRef"
        class="upload-demo"
        :action="uploadExcelUrl"
        :headers="headers"
        :on-success="handleUploadSuccess"
        :on-error="handleUploadError"
        :before-upload="handleBeforeUpload"
        :limit="1"
        :auto-upload="false"
      >
        <template #trigger>
          <el-button type="primary">选择文件</el-button>
        </template>
        
        <template #default>
          <el-button class="ml-3" type="success" @click="submitUpload">
            开始上传
          </el-button>
        </template>

        <template #tip>
          <div class="el-upload__tip">
            只能上传 xls/xlsx 格式文件，且不超过 1MB
          </div>
        </template>
      </el-upload>
    </el-dialog>
  </div>
</template>

<script setup name="Student">
import { listStudent, getStudent, delStudent, addStudent, updateStudent } from "@/api/manage/student";
import { listGrade, getMyClasses } from "@/api/manage/grade";
import { getToken } from "@/utils/auth";
import useUserStore from '@/store/modules/user';
import { ref, reactive, toRefs, getCurrentInstance, onMounted } from 'vue';

const { proxy } = getCurrentInstance();
const { tgs_status } = proxy.useDict('tgs_status');

const studentList = ref([]);
const gradeOptions = ref([]); // 班级选项列表
const teacherClassIds = ref([]); // 教师班级ID列表
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const isTeacher = ref(false); // 是否为教师角色

/* 导入相关变量 */
const uploadRef = ref(null);
const excelOpen = ref(false);
const uploadExcelUrl = ref(import.meta.env.VITE_APP_BASE_API + "/manage/student/import");
const headers = ref({ Authorization: "Bearer " + getToken() });

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    studentNumber: null,
    studentName: null,
    classId: null,
    status: null,
  },
  rules: {
    studentNumber: [
      { required: true, message: "学号不能为空", trigger: "blur" },
      { pattern: /^\d{1,10}$/, message: "学号不能超过10位数字", trigger: "blur" }
    ],
    studentName: [
      { required: true, message: "学生姓名不能为空", trigger: "blur" },
      { max: 30, message: "姓名不能超过30个字符", trigger: "blur" }
    ],
    classId: [
      { required: true, message: "班级名称不能为空", trigger: "change" }
    ],
    phone: [
      { required: true, message: "联系电话不能为空", trigger: "blur" },
      { pattern: /^\d{1,11}$/, message: "联系电话限制输入最多11位数字", trigger: "blur" }
    ],
    email: [
      { required: true, message: "邮箱不能为空", trigger: "blur" },
      { pattern: /^[^\s@]+@[^\s@]+\.[^\s@]+$/, message: "邮箱格式不正确，需包含@符号且格式为 '用户名@域名.后缀'", trigger: ["blur", "input"] },
      { max: 50, message: "邮箱不能超过50个字符", trigger: "blur" }
    ],
    status: [
      { required: true, message: "状态不能为空", trigger: "change" }
    ],
    remark: [
      { max: 500, message: "备注不能超过500个字符", trigger: "blur" }
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);

// 初始化页面时获取用户信息和班级列表
onMounted(async () => {
  try {
    await getUserInfo();
    await getGradeList();
    getList();
  } catch (error) {
    console.error("初始化页面失败:", error);
    getList();
  }
});

// 获取用户信息及角色
async function getUserInfo() {
  try {
    const userStore = useUserStore();
    const res = await userStore.getInfo();
    isTeacher.value = res.roles && res.roles.includes('teacher');
    console.log("当前用户角色:", res.roles, "是否为教师:", isTeacher.value);
  } catch (error) {
    console.error("获取用户信息失败:", error);
    isTeacher.value = false;
  }
}

/** 查询学生信息列表 */
async function getList() {
  loading.value = true;
  try {
    if (isTeacher.value && teacherClassIds.value.length > 0) {
      // 教师角色，只查询其所教班级的学生
      const params = { ...queryParams.value };
      
      // 如果查询条件中指定了班级，且该班级在教师的班级列表中
      if (params.classId && teacherClassIds.value.includes(parseInt(params.classId))) {
        // 使用指定的班级ID查询
        console.log("查询指定班级的学生:", params.classId);
      } else {
        // 使用教师所有班级ID查询
        params.classIds = teacherClassIds.value.join(',');
        params.classId = undefined;
        console.log("查询教师所有班级的学生:", params.classIds);
      }
      
      const response = await listStudent(params);
      // 过滤结果，只显示教师班级的学生
      studentList.value = response.rows.filter(student => 
        teacherClassIds.value.includes(student.classId) || 
        teacherClassIds.value.includes(parseInt(student.classId))
      );
      total.value = studentList.value.length;
    } else {
      // 管理员角色，查询所有学生
      const response = await listStudent(queryParams.value);
      studentList.value = response.rows;
      total.value = response.total;
    }
  } catch (error) {
    console.error("获取学生列表失败:", error);
  } finally {
    loading.value = false;
  }
}

// 获取班级列表
async function getGradeList() {
  try {
    if (isTeacher.value) {
      // 教师角色，只获取其任课的班级
      const response = await getMyClasses();
      gradeOptions.value = response.data || [];
      // 保存教师班级ID列表，用于学生列表过滤
      teacherClassIds.value = gradeOptions.value.map(item => item.classId);
      console.log("教师班级列表:", gradeOptions.value);
      console.log("教师班级ID列表:", teacherClassIds.value);
    } else {
      // 管理员角色，获取所有班级
      const response = await listGrade();
      gradeOptions.value = response.rows || [];
      console.log("所有班级列表:", gradeOptions.value);
    }
  } catch (error) {
    console.error("获取班级列表失败:", error);
    gradeOptions.value = [];
  }
}

// 根据班级ID获取班级名称
function getClassName(classId) {
  if (!classId) return '';
  
  // 班级ID在数据库中可能是Long类型，而前端是string类型，需要进行类型转换比较
  const grade = gradeOptions.value.find(item => item.classId.toString() === classId.toString());
  return grade ? grade.className : '';
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    studentId: null,
    studentNumber: null,
    studentName: null,
    classId: null,
    phone: null,
    email: null,
    status: null,
    remark: null,
    createTime: null,
    updateTime: null,
    createBy: null,
    updateBy: null
  };
  proxy.resetForm("studentRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  // 过滤掉学号为1000000001的学生，不允许选中
  const filteredSelection = selection.filter(item => item.studentNumber !== '1000000001');
  
  // 如果过滤后的长度和原选择不同，说明用户试图选择受保护的学生
  if (filteredSelection.length !== selection.length) {
    // 提示用户
    proxy.$modal.msgWarning("学号为1000000001的学生不允许被选中操作");
  }
  
  ids.value = filteredSelection.map(item => item.studentId);
  single.value = filteredSelection.length != 1;
  multiple.value = !filteredSelection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加学生信息";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  // 检查是否为受保护的学生
  if (row.studentNumber === '1000000001') {
    proxy.$modal.msgWarning("学号为1000000001的学生不允许被修改");
    return;
  }
  
  reset();
  // 确保先获取班级列表
  getGradeList().then(() => {
    const _studentId = row.studentId || ids.value
    getStudent(_studentId).then(response => {
      form.value = response.data;
      // 确保班级ID正确
      if (form.value.classId) {
        // 班级ID可能是不同类型，进行类型转换比较
        const classId = form.value.classId.toString();
        // 检查班级是否存在
        const grade = gradeOptions.value.find(item => item.classId.toString() === classId);
        if (grade) {
          form.value.classId = grade.classId;
        }
      }
      open.value = true;
      title.value = "修改学生信息";
    });
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["studentRef"].validate(valid => {
    if (valid) {
      // 修改操作时，检查是否为受保护的学生
      if (form.value.studentId != null) {
        // 查询原学生信息
        getStudent(form.value.studentId).then(response => {
          const originalStudent = response.data;
          if (originalStudent && originalStudent.studentNumber === '1000000001') {
            proxy.$modal.msgWarning("学号为1000000001的学生不允许被修改");
            return;
          }
          
          // 不是受保护的学生，可以进行修改
          updateStudent(form.value).then(response => {
            proxy.$modal.msgSuccess("修改成功");
            open.value = false;
            getList();
          });
        });
      } else {
        // 新增学生时，检查学号是否为受保护的学号
        if (form.value.studentNumber === '1000000001') {
          proxy.$modal.msgWarning("不允许创建学号为1000000001的学生，请使用其他学号");
          return;
        }
        
        addStudent(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  // 如果是单个删除，检查是否为受保护的学生
  if (row.studentId && row.studentNumber === '1000000001') {
    proxy.$modal.msgWarning("学号为1000000001的学生不允许被删除");
    return;
  }
  
  // 如果是批量删除，需要检查选中的学生中是否包含受保护的学生
  if (!row.studentId) {
    // 查询选中的学生
    const hasProtectedStudent = studentList.value.some(
      student => ids.value.includes(student.studentId) && student.studentNumber === '1000000001'
    );
    
    if (hasProtectedStudent) {
      proxy.$modal.msgWarning("选中的学生中包含学号为1000000001的受保护学生，不允许进行此操作");
      return;
    }
  }
  
  const _studentIds = row.studentId || ids.value;
  proxy.$modal.confirm('是否确认删除学生信息编号为"' + _studentIds + '"的数据项？').then(function() {
    return delStudent(_studentIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('manage/student/export', {
    ...queryParams.value
  }, `student_${new Date().getTime()}.xlsx`)
}

/* 打开导入对话框 */
function handleImport() {
  excelOpen.value = true;
}

/* 文件上传相关方法 */
function submitUpload() {
  uploadRef.value.submit();
}

// 上传成功回调
function handleUploadSuccess(res, file) {
  if (res.code === 200) {
    proxy.$modal.msgSuccess("导入成功");
    excelOpen.value = false;
    getList();
  } else {
    proxy.$modal.msgError(res.msg);
  }
  uploadRef.value.clearFiles();
  proxy.$modal.closeLoading();
}

// 上传失败
function handleUploadError() {
  proxy.$modal.msgError("导入失败");
  uploadRef.value.clearFiles();
  proxy.$modal.closeLoading();
}

// 上传前校验
function handleBeforeUpload(file) {
  let isExcel = false;
  const fileType = ["xls", "xlsx"];
  const fileSize = 1;
  
  if (fileType.length) {
    let fileExtension = "";
    if (file.name.lastIndexOf(".") > -1) {
      fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
    }
    isExcel = fileType.some(type => {
      if (file.type.indexOf(type) > -1) return true;
      if (fileExtension && fileExtension.indexOf(type) > -1) return true;
      return false;
    });
  } 
  
  if (!isExcel) {
    proxy.$modal.msgError(
      `文件格式不正确, 请上传${fileType.join("/")}格式文件!`
    );
    return false;
  }
  
  if (fileSize) {
    const isLt = file.size / 1024 / 1024 < fileSize;
    if (!isLt) {
      proxy.$modal.msgError(`上传文件大小不能超过 ${fileSize} MB!`);
      return false;
    }
  }
  proxy.$modal.loading("正在导入数据，请稍候...");
  return true;
}

/* 下载模板 */
function handleImportTemplate() {
  proxy.download(
    '/manage/student/importTemplate',
    {},
    `student_template_${new Date().getTime()}.xlsx`
  );
}

/** 
 * 禁止选择特定学生的行选择器
 * 添加在onMounted函数之前
 */
const rowSelectionDisabled = (row) => {
  // 返回false禁止选择，返回true允许选择
  return row.studentNumber !== '1000000001';
};
</script>